package com.qiantu.phone.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;

import com.qiantu.phone.R;

public class ColorDevicePalette extends View {
    // 画笔
    private Paint mPaint;
    private Paint mThumbPaint;
    private String progressText = null;
    private OnPaletteChangeListener mOnPaletteChangeListener;
    private double thumbCx;
    private double thumbCy;
    private double centerX;
    private double centerY;
    private double raduis;
    private double centerRaduis;
    private boolean isOpen = false;
    private int mColorTemp = 0;

    Bitmap paletteBitmap;

    public ColorDevicePalette(Context context) {
        this(context, null);
    }

    public ColorDevicePalette(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ColorDevicePalette(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new TextPaint();
        mPaint.setAntiAlias(true);

        mThumbPaint = new Paint();
        mThumbPaint.setAntiAlias(true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(!isEnabled()){
            return false;
        }
        if(!isOpen){
            return false;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
//                lastDownTime = System.currentTimeMillis();
                checkPoint(event);
                break;
            case MotionEvent.ACTION_MOVE:
                checkPoint(event);
                if (mOnPaletteChangeListener != null) {
                    mOnPaletteChangeListener.onValueChanged(mColorTemp);
                }
                break;
            case MotionEvent.ACTION_UP:
                checkPoint(event);
                if (mOnPaletteChangeListener != null) {
                    playSoundEffect(SoundEffectConstants.CLICK);
                    mOnPaletteChangeListener.onStopTrackingTouch(mColorTemp);
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return true;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        paletteBitmap = BitmapFactory.decodeResource(getResources(), isOpen ? R.mipmap.icon_devicecontrol_light_colour : R.mipmap.icon_devicecontrol_light_colour_close);
        paletteBitmap = scaleBitmap(paletteBitmap,dp2px(210),dp2px(210));
        canvas.drawBitmap(paletteBitmap,dp2px(14),dp2px(14),mPaint);
        mPaint.setColor(0xffffffff);
//        canvas.drawCircle((float) centerX, (float) centerY, (float) centerRaduis, mPaint);
        if (isOpen) {
            mThumbPaint.setColor(0xffffffff);
            canvas.drawCircle((float) thumbCx, (float) thumbCy, dp2px(14), mThumbPaint);
            mThumbPaint.setColor(mColorTemp);
            canvas.drawCircle((float) thumbCx, (float) thumbCy, dp2px(13), mThumbPaint);
        }
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //这里额外减去dp2px(14) 和 上面手指移动里的，都是需要考虑滑块再圆边缘会一半超出圆，所以需要预留空间保证滑块不被裁剪
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        centerX = thumbCx = getMeasuredWidth()/2;
        centerY = thumbCy = getMeasuredHeight()/2;
        raduis = getMeasuredWidth()/2 - dp2px(14) - 1;
        centerRaduis = dp2px(41);
    }

    public void setOpenState(boolean openState) {
        if(isOpen == openState){
            return;
        }
        isOpen = openState;
        invalidate();
    }

    /**
     * 进度监听
     */
    public interface OnPaletteChangeListener {
        /**
         * 进度监听回调
         *
         * @param progress 进度
         */
        public void onValueChanged(int colorValue);

        /**
         * 开始拖动
         */
        public void onStartTrackingTouch();

        /**
         * 停止拖动
         */
        public void onStopTrackingTouch(int colorValue);
    }

    public void setOnPaletteChangeListener(OnPaletteChangeListener changeListener) {
        this.mOnPaletteChangeListener = changeListener;
    }

    /**
     * dp转px
     *
     * @param dp dp值
     * @return px值
     */
    public int dp2px(float dp) {
        return (int) (getResources().getDimension(R.dimen.dp_1) * dp);
    }

    public double getPointAngle(){
       return Math.atan2(thumbCx - centerX,thumbCy - centerY);
    }

    public double getPonitDistance(){
        float clickDistance = (float) Math.sqrt(Math.pow(Math.abs(thumbCx - centerX), 2) + Math.pow(Math.abs(thumbCy - centerY), 2));
        return clickDistance;
    }

    public void checkPoint(MotionEvent event){
        thumbCx = event.getX();
        thumbCy = event.getY();
        getParent().requestDisallowInterceptTouchEvent(true);
        if(getPonitDistance() >= raduis){
            double angle = getPointAngle();
            thumbCx = centerX + raduis * Math.sin(angle);
            thumbCy = centerY + raduis * Math.cos(angle);
        }
//        else if(getPonitDistance() <= centerRaduis){
//            double angle = getPointAngle();
//            thumbCx = centerX + centerRaduis * Math.sin(angle);
//            thumbCy = centerY + centerRaduis * Math.cos(angle);
//        }
        mColorTemp = paletteBitmap.getPixel((int)thumbCx - dp2px(14),(int)thumbCy - dp2px(14));
        invalidate();
    }

    private Bitmap scaleBitmap(Bitmap origin, int newWidth, int newHeight) {
        if (origin == null) {
            return null;
        }
        int height = origin.getHeight();
        int width = origin.getWidth();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);// 使用后乘
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (!origin.isRecycled()) {
            origin.recycle();
        }
        return newBM;
    }
}
